require 'date'
start_time =   DateTime.now
require "yaml"
require "mongo_mapper"
require 'optparse'

$root_folder = File.expand_path(File.dirname(__FILE__))
puts "#{$root_folder}/lib/tbot.rb"
require "#{$root_folder}/lib/tbot.rb"

options = {}
optparse = OptionParser.new do|opts|
  # Set a banner, displayed at the top of the help screen.
  opts.banner = "Usage: static-cms.rb [options]"

  # Define the options, and what they do
  opts.on( '-a', '--account ACCOUNT', 'What account to run' ) do|a|
    options[:account] = a
  end

  # This displays the help screen, all programs are
  # assumed to have this option.
  opts.on( '-h', '--help', 'Display this screen' ) do
    puts opts
    exit
  end
end
optparse.parse!
#Now raise an exception if we have not found a host option
if options[:account].nil?
  puts "Please specify an account"
  raise OptionParser::MissingArgument
end

yaml_path = File.join($root_folder, "yaml", "#{options[:account].strip}.yml")
if File.exists?(yaml_path)
  settings = YAML.load_file(yaml_path)
else
  raise "The following yaml settings file doesn't exist #{yaml_path}"
  exit
end

if settings['mongodb'] == nil
  raise "Please configure MongoDB settings"
else
  mongodb_config = settings['mongodb']
end

begin
  if mongodb_config != nil
    MongoMapper.connection = Mongo::Connection.new(mongodb_config['hostname'], mongodb_config['port'])
    MongoMapper.database = mongodb_config['database']
    if mongodb_config['username'] != nil
      MongoMapper.database.authenticate(mongodb_config['username'], mongodb_config['password'])
    end
  end
rescue => e
  puts "ERROR: Could not connect to MongoDB or read config: #{e}"
  exit
end

twitter_bot = Tbot.new(settings)
twitter_bot.check_unfollow()
  
settings['search']['keywords'].each { |k|
    twitter_bot.find_friends_by_keyword(k["keyword"])
}
  
twitter_bot.dm_new_followers()

end_time = DateTime.now
run_time = ((end_time - start_time) * 24 * 60 * 60).to_i
puts "Run time: #{run_time}s"